# -*- coding: utf-8 -*-
import os
import sys
import logging
import Cookie

from google.appengine.ext import webapp
from google.appengine.ext.webapp import template

class BaseHandler(webapp.RequestHandler):
    language = 'en'
    debug = True
    
    def outputTemplate(self, values=None, view=None):  
        if values==None or view==None:
            values = {"msg":"n/a"}
            view = "msg_view"
        # TODO: add i18n support here
        if self.language == 'en':
            path = os.path.join(os.path.dirname(__file__), 'templates', view+".html")
        else:
            path = os.path.join(os.path.dirname(__file__), 'templates', view+"_"+language+".html")
        if self.debug:
            values['debug'] = True
        self.response.out.write(template.render(path, values))
        
    def getAllRequestArguments(self):
        args = self.request.arguments()
        template_values = {}
        for arg in args:
            template_values[arg] = self.request.get(arg)
        return template_values
    
    def setCookie(self, key, value):        
        cookies = Cookie.SimpleCookie(self.response.headers["Set-Cookie"])
        cookies[key] = value
        cookies[key]["path"] = "/"
        self.response.headers["Set-Cookie"] = cookies.output()     
        
    def deleteCookie(self, key):
        self.setCookie(key, '')
                
    def getCookie(self, key):
        try:        
            cookies = Cookie.SimpleCookie() 
            cookies.load(self.request.cookies)
            return cookies[key]
        except:
            logging.debug(str(sys.exc_info()))
            return ""
            
